const db = require('../db/index')
const bcrypt = require('bcryptjs')
// 获取用户信息
exports.getuserInfo = (req, res) => {
    const sql = 'select id,userName, nickName,email from ev_users where id =?'
    db.query(sql, [req.query.id], (err, results) => {
        if (err) return res.cc(err)
        if (results.length != 1) return res.cc('获取用户信息失败')
        res.send({
            message: '获取用户信息成功',
            data: results[0]
        })
    })
}
// 更新用户信息
exports.upDatauserInfo = (req, res) => {
    const sql = 'update ev_users set ? where id=?'
    db.query(sql, [req.body, req.body.id], (err, results) => {
        if (err) return res.cc(err)
        if (results.affectedRows !== 1) return res.cc('更新用户信息失败')
        res.send({
            message: '修改用户成功',
        })
    })
}
// 重置密码
exports.upDataPwd = (req, res) => {
    const sql = 'select * from ev_users where id=?'
    db.query(sql, [req.body.id], (err, results) => {
        if (err) return res.cc(err)
        if (results.length !== 1) return res.cc('用户不存在')
        const count = bcrypt.compareSync(req.body.oldval, results[0].passWord)
        if (!count) return res.cc('旧密码错误')
        const sqlstr = 'update ev_users set passWord =? where id=?'
        req.body.newval = bcrypt.hashSync(req.body.newval, 10)
        db.query(sqlstr, [req.body.newval, req.body.id], (err, results) => {
            if (err) return res.cc(err)
            if (results.affectedRows != 1) return res.cc('修改失败')
            res.send({
                message: '修改成功',
                code: '200'
            })
        })
    })
}

// 更新头像
exports.pic = (req, res) => {
    const sql = 'update ev_users set uses_pic =? where id =?'
    db.query(sql, [req.body.img, req.body.id], (err, results) => {
        if (err) return res.cc(err)
        if (results.affectedRows !== 1) return res.cc('添加失败')
        res.send({
            message: '更新头像成功',
            code: 200
        })
    })
}